from pydantic import BaseModel

# coding: utf-8
from sqlalchemy import Column, Integer, String, DateTime, event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func
from datetime import datetime
from sqlalchemy.sql import func
from typing import Optional
Base = declarative_base()
metadata = Base.metadata


class User(Base):
    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(255, 'utf8mb4_unicode_ci'), unique=True)
    hashed_password = Column(String(255, 'utf8mb4_unicode_ci'), comment='哈希密码')
    status = Column(Integer, comment='状态 0 禁用 1 正常')
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment='更新时间')
    deleted_at = Column(DateTime, comment='删除时间')
    roles = Column(String(255, 'utf8mb4_unicode_ci'), comment='规则')

@event.listens_for(User, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(User, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

class UserSchema(BaseModel):
    id: int
    username: str
    hashed_password: str
    status: int
    roles: str
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }
        from_attributes = True
